import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:microcosm_log/log_level.dart';
import 'package:microcosm_log/microcosm_log.dart';

import 'microcosm_log_platform_interface.dart';

/// An implementation of [MicrocosmLogPlatform] that uses method channels.
class MethodChannelMicrocosmLog extends MicrocosmLogPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('microcosm_log');

  final MicrocosmLogListener? logListener;

  MethodChannelMicrocosmLog(this.logListener) {
    methodChannel.setMethodCallHandler(platformCallHandler);
    //通知原生平台初始化完毕
    methodChannel.invokeMethod("onConnected");
  }

  Future<dynamic> platformCallHandler(MethodCall call) async {
    if (call.method == 'log') {
      var params = call.arguments as Map<Object?, Object?>;
      var level = params["level"] as String;
      var tag = params["tag"] as String;
      var msg = params["msg"] as String;
      var timestamp = params["timestamp"] as int;
      if (logListener != null) {
        logListener!(LogLevel.fromValue(level), tag, msg, timestamp);
      }
    }
  }
}
